<script setup lang="ts">
import {onUnmounted, ref} from 'vue';
import type { UploadCustomRequestOptions } from 'naive-ui';
import {errorMessage, successMessage, warningMessage} from '@/utils/utils';
import {
  analysisInsertAction, analysisInsertFileAction,
  analysisInsertLogAction,
  getDocumentLabelAction, getDocumentTemplateAction,
  uploadFileAction
} from '@/service/api';
import { useRouterPush } from '@/hooks/common/router';

const { routerPushByKey } = useRouterPush();

const showLoading = ref<boolean>(false);
const loadingDes = ref<string>('正在为您分析招标文件，请耐心等待...');

const docFilePath = ref<string>('');
const docFileName = ref<string>('');

// 标书文档上传
const customFileRequest = async ({ file, onFinish }: UploadCustomRequestOptions) => {
  if (file.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
    warningMessage('请上传docx格式的文档');
    return;
  }

  const formData = new FormData();
  formData.append('uploadFiles', file.file as Blob);
  formData.append('fileType', String(1));

  const { data, error } = await uploadFileAction(formData);
  if (!error) {
    docFilePath.value = data[0].filePath;
    docFileName.value = file.name.substring(0, file.name.lastIndexOf('.'));
    successMessage('上传成功');
    onFinish();
  }
};

// 移除上传的标书文档
function removeFileHandle() {
  docFilePath.value = '';
  docFileName.value = '';
}

// 开始解析
async function startAnalysisAction() {
  // await routerPushByKey('smart-eye_detail', { query: { taskId: 842, docFilePath: '/profile/biaoshu/批量化试验数字管控系统-招标文件.docx', fileName: '批量化试验数字管控系统-招标文件' } });
  // return;
  if (docFilePath.value === '') {
    warningMessage('请先上传需要解析的招标文件');
    return;
  }

  const insertParams: any = {
    type: 1, // 文件类型(1.标书 )
    materialType: 1, // 素材类型(1.标书)
    more1: docFilePath.value, // 标书基本信息文档地址
    analysisProgress: 1,
    more4: docFileName.value
  };
  showLoading.value = true;
  const { data, error } = await analysisInsertLogAction(insertParams);
  if (!error) {
    const labelParams: any = {
      file_path: docFilePath.value
    };
    const { data: labelData, error: labelError } = await getDocumentLabelAction(labelParams);
    const templateParams: any = {
      task_id: data.id,
      file_path: docFilePath.value
    };
    const { data: templateData, error: templateError } = await getDocumentTemplateAction(templateParams);
    console.log('templateData: ', templateData);
    if (!labelError && !templateError) {
      labelData.forEach((item: any) => {
        delete item.id;
        item.logId = data.id;
      });
      const { data: saveData, error: saveError } = await analysisInsertAction(labelData);

      const templateList: any[] = [];
      for (let i: number = 0; i < templateData.length; i++) {
        const templateItem: any = templateData[i];
        templateList.push({
          fileName: templateItem.substring(templateItem.lastIndexOf('/') + 1, templateItem.lastIndexOf('.')),
          filePath: templateItem,
          analysisLogId: data.id
        });
      }

      const { data: temData, error: temError } = await analysisInsertFileAction(templateList);

      if (!saveError && !temError) {
        showLoading.value = false;
        await routerPushByKey('smart-eye_detail', {
          query: {
            analysisType: 1,
            createType: 1,
            taskId: data.id,
            fileName: docFileName.value,
            docFilePath: docFilePath.value
          }
        });
      } else {
        errorMessage('获取文档标签失败');
        showLoading.value = false;
      }
    } else {
      errorMessage('获取文档标签失败');
      showLoading.value = false;
    }
  } else {
    showLoading.value = false;
  }
}

onUnmounted(() => {
  console.log('页面离开');
});
</script>

<template>
  <NSpin :show="showLoading" :description="loadingDes" :rotate="false" size="large">
    <template #icon>
      <img src="@/assets/imgs/spin-loading.gif" alt="" width="240" height="240" />
    </template>
    <div class="document-layout min-h-500px flex flex-row items-center justify-center gap-16px lt-sm:overflow-auto">
      <div class="info-box">
        <span class="info-title">欢迎使用“慧眼识标”功能</span>
        <p class="info-describe">
          帮助投标人对招标文件进行快速解析，助力客户抢占先机。重点标记废标项等关键信息，通过结构化节点的处理，将结构化内容与招标文件智能关联。
        </p>
        <div class="upload-box">
          <NUpload
            directory-dnd
            :max="1"
            accept=".docx"
            :custom-request="customFileRequest"
            @remove="removeFileHandle"
          >
            <NUploadDragger>
              <div class="mb-36px w-full flex-y-center justify-center">
                <img src="@/assets/bid-materials/word.png" alt="" width="90" height="90" />
              </div>
              <div class="flex items-center justify-center">
                <NText class="font-size-20px color-#8C8B99">将文件拖到此处，或</NText>
                <NText class="font-size-20px color-#8E7DFF">点击上传</NText>
              </div>
              <NP class="mt-8px font-size-16px" depth="3">（支持.docx格式）</NP>
            </NUploadDragger>
          </NUpload>
        </div>
        <NButton class="analysis-btn" :disabled="docFilePath === ''" @click="startAnalysisAction">开始解析</NButton>
      </div>
      <div class="eye-box">
        <img class="eye-img" src="@/assets/smart-eye/smart-eye.png" alt="" />
      </div>
    </div>
  </NSpin>
</template>

<style scoped lang="scss">
:deep(.n-spin) {
  width: auto;
  height: auto;
}
.bg-layout {
  padding: 16px 16px 0 !important;
  background: url('@/assets/smart-eye/smart-bg.png') no-repeat;
  background-size: 100% 100%;
}
.info-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 645px;
  .info-title {
    width: 100%;
    text-align: center;
    font-weight: 900;
    font-size: 48px;
    color: #836fff;
    line-height: 93px;
  }
  .info-describe {
    margin-top: 10px;
    margin-bottom: 30px;
    width: 100%;
    font-weight: 400;
    font-size: 18px;
    color: #8c8b99;
    line-height: 30px;
  }
  .upload-box {
    width: 645px;
    height: 300px;
  }
  .analysis-btn {
    margin-top: 66px;
    width: 240px;
    height: 72px;
    background: linear-gradient(90deg, #e877ae 0%, #7c73f3 100%);
    border-radius: 6px;
    font-weight: 900;
    font-size: 18px;
    color: #ffffff;
    line-height: 72px;
  }
}
:deep(.n-upload) {
  height: 100%;
}
:deep(.n-upload-trigger) {
  height: 100%;
}
:deep(.n-upload-dragger) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
}
.eye-box {
  width: 900px;
  height: 753px;
  margin-left: 80px;
  .eye-img {
    width: 100%;
    height: 100%;
  }
}
</style>
